package com.cskaoyan.config;

import com.cskaoyan.realm.CustomRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author stone
 * @date 2022/01/10 10:10
 */
@Configuration
public class ShiroConfig {

    //ShiroFilter → ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //关联的SecurityManager
        shiroFilter.setSecurityManager(securityManager);
        //重定向：默认值是login.jsp
        //shiroFilter.setLoginUrl("/admin/redirect");

        //url和拦截器之间的关系
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //anon、authc、perms
        filterChainDefinitionMap.put("/admin/auth/login", "anon");
        filterChainDefinitionMap.put("/admin/redirect", "anon");
        filterChainDefinitionMap.put("/admin/**", "authc");
        //耦合 → url → Handler方法 → 权限
        //filterChainDefinitionMap.put("/admin/admin/list", "perms[admin:admin:list]");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilter;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm customRealm,
                                                     DefaultWebSessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //如果没有设置认证器 → 会提供一个默认的认证器 → ModularRealmAuthenticator
        //securityManager.setAuthenticator();//设置认证器
        //如果没有设置授权器 → 会提供一个默认的授权器
        //securityManager.setAuthorizer();//设置授权器 → ModularRealmAuthorizer
        //如果要写自定义的认证器和授权器不建议从头开始重写，可以继承默认的认证器和授权器

        //realm需要自己提供 → 给到SecurityManager → 认证器和授权器也会获得你提供的realm
        //认证器和授权器默认的realm的来源 → 来源于SecurityManager
        //securityManager.setRealm(new CustomRealm());
        securityManager.setRealm(customRealm);

        //如果没有设置SessionManager → 会提供一个默认的SessionManager
        securityManager.setSessionManager(sessionManager);

        return securityManager;
    }

    //advisor → 提供给他shiro的核心组件SecurityManager
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }



}
